package com.dckj.auto.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.dckj.auto.common.interceptor.AuthorityAnnotation;
import com.dckj.auto.common.utils.AuthCode;
import com.dckj.auto.common.utils.JsonUtils;
import com.dckj.auto.common.utils.StringUtil;
import com.dckj.auto.common.utils.ehcache.EHCacheUtils;
import com.dckj.auto.entity.AuthUserRole;
import com.dckj.auto.service.AuthUserRoleService;
import com.xiaoleilu.hutool.setting.dialect.Props;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author WangDong123
 * @since 2018-09-03
 */
@Controller
@RequestMapping("/user/role/")
public class AuthUserRoleController {
    private Props props = new Props("config.properties","UTF-8");
    private String auth_token_cache_key = props.getStr("auth_token_cache_key");

    @Autowired
    AuthUserRoleService userRoleService;

    @AuthorityAnnotation(authority = AuthCode.USER_ROLE_INNER)
    @RequestMapping(value = "page")
    public String page(HttpServletRequest request,String userId){
        request.setAttribute("userId",userId);
        return "user-role/list";
    }

    @RequestMapping(value = "innerRole")
    @ResponseBody
    public JSONObject innerRole(String roleId,String userId){
        AuthUserRole userRole = userRoleService.selectOne(new EntityWrapper<AuthUserRole>().eq("user_id", userId));
        boolean edit = false;
        if(null == userRole){
            AuthUserRole autoUserRole = new AuthUserRole();
            autoUserRole.setId(StringUtil.getUUId());
            autoUserRole.setUserId(userId);
            autoUserRole.setRoleId(roleId);
            edit = userRoleService.insert(autoUserRole);
        }
        if(userRole!=null){
            if(userRole.getRoleId().equals(roleId)){//没有改变
                edit = true;
            }else{
                userRole.setRoleId(roleId);
                edit = userRoleService.updateById(userRole);
                EHCacheUtils cache = EHCacheUtils.getInstance();//清除当前用户的权限缓存
                cache.remove(auth_token_cache_key,userId);
            }
        }
        if(edit){
            return JsonUtils.success("分配用户角色");
        }
        return JsonUtils.error(true,"分配用户角色");
    }

}

